import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Tag,
  Avatar,
  Input,
  Select,
  DatePicker,
  Typography,
  Row,
  Col,
  Modal,
  message,
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  DownloadOutlined,
  UserOutlined,
  HeartOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { MatchRecord } from '@/types';
import { formatDate, getAvatarUrl } from '@/utils';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

const MatchRecordPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [matchRecords, setMatchRecords] = useState<MatchRecord[]>([]);
  const [selectedRecord, setSelectedRecord] = useState<MatchRecord | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [filters, setFilters] = useState({
    keyword: '',
    status: 'all',
    counselor: 'all',
  });

  // Mock data
  const mockMatchRecords: MatchRecord[] = [
    {
      id: '1',
      userA: {
        id: '1',
        nickname: '李小花',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female1',
        age: 26,
      },
      userB: {
        id: '2',
        nickname: '王明',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male1',
        age: 28,
      },
      matchScore: 92,
      matchReason: '兴趣爱好相似，年龄匹配度高',
      status: 'accepted',
      createTime: '2024-01-20T14:25:00Z',
      counselor: '张顾问',
      notes: '双方都表现出较高的兴趣',
    },
    {
      id: '2',
      userA: {
        id: '3',
        nickname: '张丽',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female2',
        age: 24,
      },
      userB: {
        id: '4',
        nickname: '陈志强',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male2',
        age: 30,
      },
      matchScore: 85,
      matchReason: '教育背景相当，地理位置接近',
      status: 'rejected',
      createTime: '2024-01-19T16:45:00Z',
      counselor: '李顾问',
      notes: '用户B对年龄差距有顾虑',
    },
    {
      id: '3',
      userA: {
        id: '5',
        nickname: '刘芳',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female3',
        age: 29,
      },
      userB: {
        id: '6',
        nickname: '赵华',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male3',
        age: 32,
      },
      matchScore: 78,
      matchReason: '职业互补，价值观契合',
      status: 'pending',
      createTime: '2024-01-18T11:30:00Z',
      counselor: '王顾问',
      notes: '等待双方回应',
    },
  ];

  const getStatusTag = (status: string) => {
    const statusMap = {
      pending: { color: 'orange', text: '待回应' },
      accepted: { color: 'green', text: '已接受' },
      rejected: { color: 'red', text: '已拒绝' },
      expired: { color: 'gray', text: '已过期' },
    };
    const config = statusMap[status as keyof typeof statusMap];
    return <Tag color={config?.color}>{config?.text}</Tag>;
  };

  const columns: ColumnsType<MatchRecord> = [
    {
      title: '匹配ID',
      dataIndex: 'id',
      key: 'id',
      width: 100,
      render: (id) => <Text code>#{id}</Text>,
    },
    {
      title: '用户A',
      key: 'userA',
      width: 150,
      render: (_, record) => (
        <Space>
          <Avatar
            size={32}
            src={getAvatarUrl(record.userA.avatar)}
            icon={<UserOutlined />}
          />
          <div>
            <div>{record.userA.nickname}</div>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              {record.userA.age}岁
            </Text>
          </div>
        </Space>
      ),
    },
    {
      title: '用户B',
      key: 'userB',
      width: 150,
      render: (_, record) => (
        <Space>
          <Avatar
            size={32}
            src={getAvatarUrl(record.userB.avatar)}
            icon={<UserOutlined />}
          />
          <div>
            <div>{record.userB.nickname}</div>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              {record.userB.age}岁
            </Text>
          </div>
        </Space>
      ),
    },
    {
      title: '匹配度',
      dataIndex: 'matchScore',
      key: 'matchScore',
      width: 100,
      render: (score) => (
        <div style={{ textAlign: 'center' }}>
          <div style={{ 
            color: score >= 90 ? '#52c41a' : score >= 80 ? '#fa8c16' : '#1890ff',
            fontWeight: 'bold'
          }}>
            {score}%
          </div>
        </div>
      ),
      sorter: (a, b) => a.matchScore - b.matchScore,
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      render: (_, record) => getStatusTag(record.status),
      filters: [
        { text: '待回应', value: 'pending' },
        { text: '已接受', value: 'accepted' },
        { text: '已拒绝', value: 'rejected' },
        { text: '已过期', value: 'expired' },
      ],
      onFilter: (value, record) => record.status === value,
    },
    {
      title: '匹配顾问',
      dataIndex: 'counselor',
      key: 'counselor',
      width: 100,
    },
    {
      title: '创建时间',
      key: 'createTime',
      width: 160,
      render: (_, record) => formatDate(record.createTime, 'MM-DD HH:mm'),
      sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => (
        <Space>
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        </Space>
      ),
    },
  ];

  const handleViewDetail = (record: MatchRecord) => {
    setSelectedRecord(record);
    setDetailModalVisible(true);
  };

  const handleSearch = async () => {
    try {
      setLoading(true);
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 500));
      
      let filtered = mockMatchRecords;
      
      if (filters.keyword) {
        filtered = filtered.filter(record =>
          record.userA.nickname.includes(filters.keyword) ||
          record.userB.nickname.includes(filters.keyword) ||
          record.counselor?.includes(filters.keyword)
        );
      }
      
      if (filters.status !== 'all') {
        filtered = filtered.filter(record => record.status === filters.status);
      }
      
      if (filters.counselor !== 'all') {
        filtered = filtered.filter(record => record.counselor === filters.counselor);
      }
      
      setMatchRecords(filtered);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleExport = () => {
    message.info('正在导出配对记录...');
    // Simulate export
    setTimeout(() => {
      message.success('导出成功');
    }, 2000);
  };

  useEffect(() => {
    handleSearch();
  }, []);

  return (
    <div className="page-container">
      <div className="page-header">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <Title level={4} className="page-title">配对记录</Title>
            <Text className="page-description">
              查看所有匹配记录和结果统计，支持按多种条件筛选
            </Text>
          </div>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>
            导出记录
          </Button>
        </div>
      </div>

      {/* Filters */}
      <Card style={{ marginBottom: '16px' }} bodyStyle={{ paddingBottom: '0' }}>
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={8} md={6}>
            <Input
              placeholder="搜索用户昵称或顾问"
              prefix={<SearchOutlined />}
              value={filters.keyword}
              onChange={(e) => setFilters({ ...filters, keyword: e.target.value })}
              onPressEnter={handleSearch}
            />
          </Col>
          <Col xs={24} sm={8} md={4}>
            <Select
              placeholder="状态"
              value={filters.status}
              onChange={(value) => setFilters({ ...filters, status: value })}
              style={{ width: '100%' }}
            >
              <Select.Option value="all">全部状态</Select.Option>
              <Select.Option value="pending">待回应</Select.Option>
              <Select.Option value="accepted">已接受</Select.Option>
              <Select.Option value="rejected">已拒绝</Select.Option>
              <Select.Option value="expired">已过期</Select.Option>
            </Select>
          </Col>
          <Col xs={24} sm={8} md={4}>
            <Select
              placeholder="匹配顾问"
              value={filters.counselor}
              onChange={(value) => setFilters({ ...filters, counselor: value })}
              style={{ width: '100%' }}
            >
              <Select.Option value="all">全部顾问</Select.Option>
              <Select.Option value="张顾问">张顾问</Select.Option>
              <Select.Option value="李顾问">李顾问</Select.Option>
              <Select.Option value="王顾问">王顾问</Select.Option>
              <Select.Option value="陈顾问">陈顾问</Select.Option>
            </Select>
          </Col>
          <Col xs={24} sm={24} md={6}>
            <RangePicker
              placeholder={['开始时间', '结束时间']}
              style={{ width: '100%' }}
            />
          </Col>
          <Col xs={24} sm={24} md={4}>
            <Space>
              <Button type="primary" onClick={handleSearch} loading={loading}>
                搜索
              </Button>
              <Button onClick={() => setFilters({ keyword: '', status: 'all', counselor: 'all' })}>
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* Statistics Cards */}
      <Row gutter={[16, 16]} style={{ marginBottom: '16px' }}>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                {matchRecords.length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>总匹配数</div>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                {matchRecords.filter(r => r.status === 'accepted').length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>成功匹配</div>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#fa8c16' }}>
                {matchRecords.filter(r => r.status === 'pending').length}
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>待回应</div>
            </div>
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                {matchRecords.length > 0 ? Math.round(matchRecords.filter(r => r.status === 'accepted').length / matchRecords.length * 100) : 0}%
              </div>
              <div style={{ fontSize: '12px', color: '#8c8c8c' }}>成功率</div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* Records Table */}
      <Card>
        <Table
          columns={columns}
          dataSource={matchRecords}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* Detail Modal */}
      <Modal
        title="配对详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedRecord && (
          <div>
            <div style={{ textAlign: 'center', marginBottom: '24px' }}>
              <Space size={32}>
                <div>
                  <Avatar
                    size={64}
                    src={getAvatarUrl(selectedRecord.userA.avatar)}
                    icon={<UserOutlined />}
                  />
                  <div style={{ marginTop: '8px' }}>
                    <Text strong>{selectedRecord.userA.nickname}</Text>
                    <br />
                    <Text type="secondary">{selectedRecord.userA.age}岁</Text>
                  </div>
                </div>
                
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                  <HeartOutlined style={{ fontSize: '32px', color: '#eb2f96' }} />
                  <div style={{ marginTop: '8px', textAlign: 'center' }}>
                    <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#1890ff' }}>
                      {selectedRecord.matchScore}%
                    </div>
                    <Text type="secondary" style={{ fontSize: '12px' }}>匹配度</Text>
                  </div>
                </div>
                
                <div>
                  <Avatar
                    size={64}
                    src={getAvatarUrl(selectedRecord.userB.avatar)}
                    icon={<UserOutlined />}
                  />
                  <div style={{ marginTop: '8px' }}>
                    <Text strong>{selectedRecord.userB.nickname}</Text>
                    <br />
                    <Text type="secondary">{selectedRecord.userB.age}岁</Text>
                  </div>
                </div>
              </Space>
            </div>

            <div>
              <Space direction="vertical" style={{ width: '100%' }} size="middle">
                <div>
                  <Text strong>匹配理由：</Text>
                  <Text>{selectedRecord.matchReason}</Text>
                </div>
                
                <div>
                  <Text strong>当前状态：</Text>
                  {getStatusTag(selectedRecord.status)}
                </div>
                
                <div>
                  <Text strong>负责顾问：</Text>
                  <Text>{selectedRecord.counselor}</Text>
                </div>
                
                <div>
                  <Text strong>创建时间：</Text>
                  <Text>{formatDate(selectedRecord.createTime)}</Text>
                </div>
                
                {selectedRecord.notes && (
                  <div>
                    <Text strong>备注说明：</Text>
                    <Text>{selectedRecord.notes}</Text>
                  </div>
                )}
              </Space>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default MatchRecordPage;